using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ymicroCoreNet.data;

namespace microDB
{
    public partial class frmMain : Form
    {
        private controlData ctData = null;
        private string filePathName = "";

        public frmMain()
        {
            InitializeComponent();
        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fileName = "";
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "SQL(*.sql)|*.sql";

            if(openDialog.ShowDialog() == DialogResult.OK)
            {
                fileName = openDialog.FileName;
                filePathName = fileName;
                this.Text = "小型数据查看工具 (" + filePathName + ")";
            }
            else
            {
                return;
            }

            if (!fileName.Equals(""))
            {
                rtxtSQL.Text = File.ReadAllText(fileName);
            }
        }

        private void newLinkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ctData = new controlData();

            treeDataBase.Nodes.Clear();

            string fileName = "";
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Access(*.mdb)|*.mdb";
            // openDialog.Filter = "Access(*.mdb)|*.mdb|Sqlite(*.db)|*.db";
            DataTable dt = null;

            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                fileName = openDialog.FileName;
            }
            else
            {
                return;
            }
            
            if (!fileName.Equals(""))
            {
                string executeName = fileName.Substring(fileName.LastIndexOf("."));
                
                switch (executeName)
                {
                    case ".mdb":
                        ctData.DBType = "access";
                        ctData.DBPath = fileName;
                        break;

                    case ".db":
                        ctData.DBPath = fileName;
                        ctData.DBType = "sqlite";
                        break;

                    default:
                        ctData.DBType = "";
                        ctData.DBPath = "";
                        return;
                }
            }

            try {
                loadTreeNode();
            }
            catch(Exception ex)
            {
                MessageBox.Show("文件格式错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void 日期ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rtxtSQL.AppendText(DateTime.Now.ToString().Replace("/", "-"));
        }

        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(rtxtSQL.Focused) rtxtSQL.Select(0, rtxtSQL.Rtf.Length);
        }

        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rtxtSQL.Paste();
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (rtxtSQL.Focused == true)
            {
                Clipboard.SetData(DataFormats.Rtf, rtxtSQL.SelectedRtf);
            }

            if(tabDataInfor.Focused == true)
            {
                int sign = 0;
                StringBuilder strBuilder = new StringBuilder();
                for(int rowscount = 0; rowscount < tabDataInfor.Rows.Count; rowscount++)
                {
                    for(int colscount = 0; colscount < tabDataInfor.Columns.Count; colscount++)
                    {
                        if(tabDataInfor[colscount, rowscount].Selected == true)
                        {
                            strBuilder.Append(tabDataInfor[colscount, rowscount].Value.ToString() + "\t");
                            sign = 1;
                        }
                    }

                    if(strBuilder.Length > 0 && sign == 1)
                    {
                        strBuilder.Append("\r\n");
                        sign = 0;
                    }
                }

                Clipboard.SetData(DataFormats.Text, strBuilder.ToString());
            }
        }

        private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (rtxtSQL.Focused == true)
            {
                Clipboard.SetData(DataFormats.Rtf, rtxtSQL.SelectedRtf);
                rtxtSQL.SelectedRtf = "";
            }
        }

        private void 撤消ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void treeDataBase_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            rtxtSQL.Clear();
            rtxtSQL.AppendText("select top 100 * from " + treeDataBase.SelectedNode.Text);

            string[] strList = { "select", "from" };

            // richTextBoxColorHandler rtch = new richTextBoxColorHandler(rtxtSQL, strList, Color.Blue);
        }

        private void 运行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ctData != null)
            {
                DataTable dt = null;
                dt = ctData.Select(rtxtSQL.Text.Trim());

                if (dt != null) tabDataInfor.DataSource = dt;

                for (int i = 0; i < tabDataInfor.Columns.Count; i++)
                {
                    tabDataInfor.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
            }
            else
            {
                MessageBox.Show("请链接数据库文件！", "错误警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cutLinkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeDataBase.Nodes.Clear();
            ctData = null;
        }

        private void 查找ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void saveasFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fileName = "";
            fileName = saveDialogShow();

            if (!fileName.Equals(""))
            {
                System.IO.File.WriteAllText(fileName, rtxtSQL.Text, Encoding.UTF8);
                filePathName = fileName;
                this.Text = "小型数据查看工具 (" + filePathName + ")";
            }
        }

        private void saveFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (filePathName.Equals(""))
            {
                string fileName = "";

                fileName = saveDialogShow();

                if (fileName.Equals("")) return;
                
                filePathName = fileName;
            }

            if (!filePathName.Equals(""))
            {
                System.IO.File.WriteAllText(filePathName, rtxtSQL.Text, Encoding.UTF8);
                this.Text = "小型数据查看工具 (" + filePathName + ")";
            }
            else
            {
                MessageBox.Show("请选择有效文件路径！", "错误警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void treeDataBase_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point clickPoint = new Point(e.X, e.Y);
                TreeNode treeNode = treeDataBase.GetNodeAt(clickPoint);

                if (treeNode == null) return;

                treeNode.ContextMenuStrip = conMenuTreeDataBase;
                treeDataBase.SelectedNode = treeNode;
            }
        }

        private void tabDataInfor_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                dataGridViewSelect(e);
            }

            /*
            if (e.Button == MouseButtons.Right)
            {
                conMenuDataGridViewCopy.Show(e.X, e.Y);
            }
            */
        }

        private void 删除表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL;
            
            if(MessageBox.Show("确认删除？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                return;
            }

            strSQL = "drop table " + treeDataBase.SelectedNode.Text;

            int result = ctData.exec(strSQL);

            if(result == -1000)
            {
                MessageBox.Show("操作失败！", "错误警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            treeDataBase.SelectedNode.Remove();
        }
        

        private void 复制数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder strBuilder = new StringBuilder();
            for (int rowscount = 0; rowscount < tabDataInfor.Rows.Count; rowscount++)
            {
                for (int colscount = 0; colscount < tabDataInfor.Columns.Count; colscount++)
                {
                    if (tabDataInfor[colscount, rowscount].Selected == true)
                    {
                        strBuilder.Append(tabDataInfor[colscount, rowscount].Value.ToString() + "\t");
                    }
                }

                if (strBuilder.Length > 0)
                {
                    strBuilder.Append("\r\n");
                }
            }

            Clipboard.SetData(DataFormats.Text, strBuilder.ToString());
        }






        // 自建方法
        private string saveDialogShow()
        {
            string fileName = "";

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "SQL(*.sql)|*.sql";

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                fileName = saveDialog.FileName;
            }

            return fileName;
        }

        private void loadTreeNode()
        {
            DataTable dt = null;
            ctData.OpenConn();

            dt = ctData.GetSchema();

            Console.WriteLine("共计 " + dt.Rows.Count + " 张表，每张表共有 " + dt.Columns.Count + " 列！");
            Console.WriteLine("*************************************************");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i][3].ToString() == "TABLE")
                {
                    treeDataBase.Nodes.Add(dt.Rows[i][2].ToString());
                }

                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    Console.Write(j.ToString() + ": " + dt.Rows[i][j].ToString());
                    Console.WriteLine("\t");
                }

                Console.WriteLine("-------------------------------------------------");
            }
        }

        private void dataGridViewSelect(DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == -1)
            {
                tabDataInfor.ClearSelection();

                for (int i = 0; i < tabDataInfor.Columns.Count; i++)
                {
                    tabDataInfor[i, e.RowIndex].Selected = true;
                }
            }
            else if (e.RowIndex == -1 && e.ColumnIndex >= 0)
            {
                tabDataInfor.ClearSelection();

                for (int i = 0; i < tabDataInfor.Rows.Count; i++)
                {
                    tabDataInfor[e.ColumnIndex, i].Selected = true;
                }
            }
        }

        
    }
}
